package com.ruoyi.project.system.user.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.security.AuthorizationUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.post.service.IPostService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class UserController extends BaseController
{
    private String prefix = "system/user";

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPostService postService;




//    @RequiresRoles(value = {Constants.ROLE_ROLE_KEY_ADMIN,Constants.ROLE_ROLE_KEY_FINANCE},logical = Logical.OR)
//    @RequiresUser
    //跳转充值页面
    @GetMapping("/recharge/{userId}")
    public String toVariation(@PathVariable("userId") Long userId, Model model){

        model.addAttribute("userId", userId);

        return  prefix+"/recharge";
    }



//    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user(Model model)
    {
        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        Integer stateUser = userService.stateUser(loginUser).getStateUser();
        model.addAttribute("loginUser",loginUser);
        model.addAttribute("stateUser",stateUser);
        return prefix + "/user";
    }

//    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(User user)
    {
        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        startPage();
        if ("admin".equals(loginUser)){
            List<User> list = userService.selectUserList(user);
            return getDataTable(list);
        }else {
            user.setCreateBy(loginUser);
            List<User> list = userService.selectByCreateBy(user);
            return getDataTable(list);
        }
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        List<User> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

//    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
//    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated User user)
    {

        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        User userLogin = userService.stateUser(loginUser);
        if (!"admin".equals(loginUser)){
            BigDecimal spendAdd = user.getSpend();
            BigDecimal spend = userLogin.getSpend();
            if (spend.compareTo(spendAdd)>0){
                throw new ServiceException("子账号单价不得小于本账号单价");
            }
        }
        Integer stateUser = userLogin.getStateUser();
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        if (stateUser==1){
            throw new ServiceException("您没有权限添加用户");
        }
//        BigDecimal amount = userLogin.getAmount();
//        //子账号余额
//        BigDecimal amountAdd = user.getAmount();
//        //二级账号剩余的余额
//        BigDecimal newAmount = amount.subtract(amountAdd);
//        if (newAmount.compareTo(BigDecimal.ZERO) < 0){
//            throw new ServiceException("余额不足以创建子账号！");
//        }

        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
//    @RequiresPermissions("system:user:edit")
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        userService.checkUserDataScope(userId);
        List<Role> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated User user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return toAjax(userService.updateUser(user));
    }

//    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

//    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(User user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (userService.resetUserPwd(user) > 0)
        {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue())
            {
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
//    @RequiresPermissions("system:user:edit")
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        User user = userService.selectUserById(userId);
        // 获取用户所属的角色列表
        List<Role> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", user);
        mmap.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
//    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return success();
    }

//    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        if (ArrayUtils.contains(Convert.toLongArray(ids), getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user)
    {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(User user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(User user)
    {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(User user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.changeStatus(user));
    }

    @PostMapping("/updateStateUser0")
    @ResponseBody
    public AjaxResult updateStateUser0(Long userId)
    {
        return toAjax(userService.updateStateUser0(userId));
    }

    @PostMapping("/updateStateUser1")
    @ResponseBody
    public AjaxResult updateStateUser1(Long userId)
    {
        return toAjax(userService.updateStateUser1(userId));
    }


//    @PostMapping("/updateRecharge")
//    @ResponseBody
//    public AjaxResult updateRecharge(BigDecimal recharge,Long userId)
//    {
//        return toAjax(userService.updateRecharge(recharge,userId));
//    }

    //充值
    @PostMapping("/recharge")
    @ResponseBody
    public AjaxResult Recharge(Long userId,BigDecimal recharge)
    {
        if (recharge.compareTo(BigDecimal.ZERO) < 0){
            throw new ServiceException("充值金额不能为负数！");
        }
        // 获取当前的用户信息
        User currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户名称
        String loginUser = currentUser.getLoginName();
        User user = userService.selectUserById(userId);
        //获取上级账号信息
        User userCreateBy = userService.stateUser(user.getCreateBy());
//        System.out.println(user.getCreateBy());
        if (!"admin".equals(loginUser)) {

        if (!"admin".equals(user.getCreateBy())){
            //上级账号余额
            BigDecimal amount = userCreateBy.getAmount();
            //上级账号余额减去充值的钱,剩余的钱
            BigDecimal subtract = amount.subtract(recharge);
            if (subtract.compareTo(BigDecimal.ZERO) < 0){
                throw new ServiceException("账号余额不足");
            }
            //修改上级账号余额
            userService.updateAmount(subtract,user.getCreateBy());

        }
        }
        BigDecimal oldAmount = user.getAmount();
        BigDecimal newAmount = oldAmount.add(recharge);
        int recharge1 = userService.recharge(recharge, userId,newAmount);
        if (recharge1>0){
            return AjaxResult.success("充值成功");
        }else {
            return AjaxResult.error("充值失败");
        }
    }
}